package com.jmail.sample;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Button;
import org.eclipse.nebula.widgets.gallery.Gallery;
import org.eclipse.nebula.widgets.gallery.DefaultGalleryItemRenderer;
import org.eclipse.nebula.widgets.gallery.DefaultGalleryGroupRenderer;
import org.eclipse.nebula.widgets.gallery.GalleryItem;

import com.jmail.model.entity.User;
import com.skn.constant.Constant;
import com.swtdesigner.SWTResourceManager;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class Login extends Shell {
	
	private Object result;
	
	private Text txtUsername;
	private Text txtPassword;
	private Combo cmbMailHost;
	private Label lblUserNameStar;
	private Label lblPasswordStar;
	private Label lblMailHostStar;
	
	private String[] lstMailHost;
	private String[] lstMailHostDisp;
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			Display display = Display.getDefault();
			Login shell = new Login(display);
			shell.open();
			shell.layout();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the shell.
	 * @param display
	 */
	public Login(Display display) {
		super(display, SWT.SHELL_TRIM);
		
		createContents();
		
		init();
	}

	/**
	 * Create contents of the shell.
	 */
	protected void createContents() {
		setText("Sign in");
		setSize(515, 363);

		Label lblUserName = new Label(this, SWT.NONE);
		lblUserName.setBounds(125, 84, 68, 13);
		lblUserName.setText("User name:");
		
		txtUsername = new Text(this, SWT.BORDER);
		txtUsername.setBounds(199, 81, 180, 19);
		
		txtPassword = new Text(this, SWT.BORDER);
		txtPassword.setBounds(199, 120, 180, 19);
		
		Label lblPassword = new Label(this, SWT.NONE);
		lblPassword.setText("Password:");
		lblPassword.setBounds(125, 123, 68, 13);
		
		Label lblMailHost = new Label(this, SWT.NONE);
		lblMailHost.setText("Mail host:");
		lblMailHost.setBounds(125, 162, 68, 13);
		
		cmbMailHost = new Combo(this, SWT.NONE);
		cmbMailHost.setBounds(199, 159, 180, 21);
		
		Button btnSignIn = new Button(this, SWT.NONE);
		btnSignIn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				signIn();
			}
		});
		btnSignIn.setBounds(199, 193, 84, 23);
		btnSignIn.setText("Sign In");
		
		Label label = new Label(this, SWT.NONE);
		label.setImage(SWTResourceManager.getImage(Login.class, "/com/jmail/images/email1_120x101.png"));
		label.setBounds(10, 10, 128, 93);
		
		Label label_1 = new Label(this, SWT.NONE);
		label_1.setImage(SWTResourceManager.getImage(Login.class, "/com/jmail/images/Email5_110x110.png"));
		label_1.setBounds(195, 230, 128, 93);
		
		Label label_2 = new Label(this, SWT.NONE);
		label_2.setImage(SWTResourceManager.getImage(Login.class, "/com/jmail/images/email7_110x80.png"));
		label_2.setBounds(397, 0, 110, 93);
		
		Label label_3 = new Label(this, SWT.NONE);
		label_3.setImage(SWTResourceManager.getImage(Login.class, "/com/jmail/images/Email6_110x110.png"));
		label_3.setBounds(369, 181, 128, 126);
		
		Label label_4 = new Label(this, SWT.NONE);
		label_4.setImage(SWTResourceManager.getImage(Login.class, "/com/jmail/images/email8_110x110.png"));
		label_4.setBounds(10, 181, 137, 117);
		
		lblUserNameStar = new Label(this, SWT.NONE);
		lblUserNameStar.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL));
		lblUserNameStar.setText("*");
		lblUserNameStar.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		lblUserNameStar.setBounds(381, 81, 8, 13);
		
		lblPasswordStar = new Label(this, SWT.NONE);
		lblPasswordStar.setText("*");
		lblPasswordStar.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		lblPasswordStar.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL));
		lblPasswordStar.setBounds(381, 120, 8, 13);
		
		lblMailHostStar = new Label(this, SWT.NONE);
		lblMailHostStar.setText("*");
		lblMailHostStar.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		lblMailHostStar.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.NORMAL));
		lblMailHostStar.setBounds(381, 159, 8, 13);
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
	
	public Object openDialog() {
		this.open();
		this.layout();

		while (!this.isDisposed()) {
			if (!getDisplay().readAndDispatch()) {
				getDisplay().sleep();
			}
		}
		return result;
	}
	
	private void init() {
		lstMailHost = new String[] {Constant.HOST_GMAIL, Constant.HOST_YAHOO_MAIL};
		lstMailHostDisp = new String[] {"GMail", "Yahoo Mail"};
		
		this.cmbMailHost.setItems(lstMailHostDisp);
		
		this.lblUserNameStar.setText("");
		this.lblPasswordStar.setText("");
		this.lblMailHostStar.setText("");
		
		this.txtUsername.setText("huanph504");
		this.txtPassword.setText("Huanpham");
		this.cmbMailHost.select(0);
	}
	
	private void signIn() {
		this.lblUserNameStar.setText("");
		this.lblPasswordStar.setText("");
		this.lblMailHostStar.setText("");
		
		if (this.txtUsername.getText().trim().equals("")) {
			this.lblUserNameStar.setText("*");
			this.txtUsername.setFocus();
			return;
		} else if (this.txtPassword.getText().trim().equals("")) {
			this.lblPasswordStar.setText("*");
			this.txtPassword.setFocus();
			return;
		} else if (this.cmbMailHost.getSelectionIndex() < 0) {
			this.lblMailHostStar.setText("*");
			this.cmbMailHost.setFocus();
			return;
		}
		
		if (!this.checkUser(this.txtUsername.getText(), this.txtPassword.getText(), Constant.PROTOCOL_SMTP + "." + lstMailHost[this.cmbMailHost.getSelectionIndex()])) {
			MessageBox mBox = new MessageBox(getShell(), SWT.OK | SWT.ICON_INFORMATION);
			mBox.setText("Info");
			mBox.setMessage("Login failed!");
		} else {
			System.out.println("Login successfully!");
		}
	    
		this.result = new User(this.txtUsername.getText(), this.txtPassword.getText(), lstMailHost[this.cmbMailHost.getSelectionIndex()]);
		dispose();
	}
	
	private boolean checkUser(final String username, final String password, String mailHost) {
		Properties props = new Properties();
        props.put("mail.transport.protocol", Constant.PROTOCOL_SMTP);
        props.put("mail.smtp.host", mailHost);
        props.put("mail.smtp.auth", "true");

		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		};
		
		Session session = Session.getDefaultInstance(props, auth);

	    Transport transport = null;
	    
		try {
			transport = session.getTransport();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			return false;
		}
        try {
			transport.connect();
			transport.close();
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
}
